#include "vdu.h"

#include <ncurses.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdarg.h>

#define MULTI 0x17

static int bytes_remaining = 0;

int control_bytes_required[32] = 
{
	0,1,0,0,
	0,0,0,0,
	0,0,0,0,
	0,0,0,0,
	0,1,2,5,
	0,0,1,9,
	8,5,0,0,
	4,4,0,2
};

void vdu_init()
{
	initscr();
	timeout(50);
}

void vdu_destroy()
{
	endwin();
}

char vdu_getchar(void)
{
	return getchar();
}

void vdu_putchar(const char c)
{
	if (bytes_remaining == 0) 
	{
		if ((c > 31) || (c == 10) || (c == 13))
		{
			putchar(c);
		}
	
		if (c < 32)
		{
			bytes_remaining = control_bytes_required[(int)c];
		}
	}
	else
	{
		bytes_remaining--;
	}
}

int vdu_printf(const char *fmt, ...)
{
	char buff[2048];
	va_list args;
	va_start(args, fmt);
	int size = vsnprintf(buff, 2048, fmt, args);
	
	int i;
	for (i=0; i<size; i++)
	{
		vdu_putchar(buff[i]);
	}
	
	va_end(args);
	return size;
}
